#coding:utf8
from __future__ import absolute_import
from djcelery.schedulers import DatabaseScheduler, ModelEntry
from cvirt.manager.models import CvirtPeriodicTask

from anyjson import serialize


class CvirtModelEntry(ModelEntry):
    @classmethod
    def from_entry(cls, name, skip_fields=("relative", "options"), **entry):
        options = entry.get("options") or {}
        fields = dict(entry)
        for skip_field in skip_fields:
            fields.pop(skip_field, None)
        schedule = fields.pop("schedule")
        model_schedule, model_field = cls.to_model_schedule(schedule)
        fields[model_field] = model_schedule
        fields["args"] = serialize(fields.get("args") or [])
        fields["kwargs"] = serialize(fields.get("kwargs") or {})
        fields["queue"] = options.get("queue")
        fields["exchange"] = options.get("exchange")
        fields["routing_key"] = options.get("routing_key")
        return cls(CvirtPeriodicTask._default_manager.update_or_create(name=name,
                                                                  defaults=fields))


class CvirtDatabaseScheduler(DatabaseScheduler):
    Model = CvirtPeriodicTask
    Entry = CvirtModelEntry